// pages/room-test/index.tsx
import Taro from '@tarojs/taro'
import { View, Button, Text, Input } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { useRoomService } from '../../hooks/useRoomService'

// ========================
// 🧩 房间资源类型
// ========================
interface RoomResource {
  status: string
  playerIps: string[]
  playerPanels: Record<string, any>
  blackBag: any[]
  CardListA: any[]
  CardListB: any[]
  CardListC: any[]
  CardListD: any[]
  gemPositon: string[]
  gemSource: any[]
  currentPlayerIp: string
  nextPlayerIp: string
  round: number
  keepCards: Record<string, any[]>
  buyCards: Record<string, any[]>
  gameConfig: any
}

// ========================
// 🧪 主组件
// ========================
export default function TaroRoomTest() {
  const [userIp, setuserIp] = useState<string>('')
  const [command, setCommand] = useState<string>('')
  const [commandPayload, setCommandPayload] = useState<string>('')
  const [roomId, setRoomId] = useState<string>('') // 添加房间ID状态

  const {
    connectionStatus,
    roomResource,
    isConnected,
    createRoom,
    connectWebSocket,
    joinRoom,
    sendGameCommand,
    disconnectWebSocket,
    getRoomResource,
    addPlayerToRoom,
    cleanup
  } = useRoomService({
    roomId, // 传递roomId
    onRoomResourceUpdate: (resource) => {
      // console.log('📦 房间资源更新:', resource)
    },
    onRoomCommand: (cmd) => {
      // console.log('📦 房间指令:', cmd)
    }
  })

  // 创建房间
  const handleCreateRoom = async () => {
    const result = await createRoom()
    if (result.success && result.roomId) {
      setRoomId(result.roomId)
    }
  }

  // 连接 WebSocket
  const handleConnectWebSocket = () => {
    connectWebSocket()
  }

  // 添加玩家
  const handleAddPlayer = async () => {
    await addPlayerToRoom(userIp)
  }

  // 获取房间资源
  const handleGetRoomResource = async () => {
    await getRoomResource()
  }

  // 发送游戏指令
  const handleSendGameCommand = async () => {
    let payload = {}
    try {
      payload = commandPayload ? JSON.parse(commandPayload) : {}
    } catch (e) {
      Taro.showToast({ title: '参数格式错误', icon: 'none' })
      return
    }
    
    await sendGameCommand(command, payload)
  }

  // 清理
  useEffect(() => {
    return () => {
      cleanup()
    }
  }, [cleanup])

  // 跳转到自身页面
  const handleNavigateToSelf = () => {
    Taro.navigateTo({
      url: '/pages/index/index'
    })
  }

  // 跳转到main页面并传递房间号
  const handleNavigateToMain = () => {
    if (roomId) {
      
      Taro.navigateTo({
        url: `/pages/main/index?roomId=${roomId}`
      })
    } else {
      Taro.showToast({ title: '请先创建房间', icon: 'none' })
    }
  }

  return (
    <View style={{ padding: '20px' }}>
      <Text style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '20px' }}>
        Taro 房间测试 (STOMP)
      </Text>

      {/* 添加跳转到自身的按钮 */}
      <View style={{ marginBottom: '20px' }}>
        <Button onClick={handleNavigateToSelf} type='primary'>
          跳转到首页
        </Button>
      </View>

      {/* 添加跳转到main页面的按钮 */}
      <View style={{ marginBottom: '20px' }}>
        <Button onClick={handleNavigateToMain} type='primary'>
          跳转到游戏页面
        </Button>
      </View>

      <View style={{ marginBottom: '20px' }}>
        <Button onClick={handleCreateRoom}>创建房间</Button>
        {roomId && <Text style={{ marginLeft: '10px' }}>ID: {roomId}</Text>}
      </View>

      <View style={{ marginBottom: '20px' }}>
        <Button onClick={handleConnectWebSocket} type='primary' style={{ marginRight: '10px' }}>
          连接
        </Button>
        <Button onClick={disconnectWebSocket}>断开</Button>
        <Text style={{ display: 'block', marginTop: '10px' }}>
          状态: {connectionStatus}
        </Text>
      </View>

      <View style={{ marginBottom: '20px' }}>
        <Input
          placeholder='玩家ID'
          value={userIp}
          onInput={(e) => setuserIp(e.detail.value)}
          style={{ border: '1px solid #ccc', padding: '8px', marginBottom: '8px' }}
        />
        <Button onClick={handleAddPlayer} type='primary' disabled={!roomId}>
          添加玩家
        </Button>
      </View>

      <View style={{ marginBottom: '20px' }}>
        <Button onClick={handleGetRoomResource} type='primary' disabled={!roomId}>
          获取房间资源
        </Button>
        {roomResource && (
          <View style={{ marginTop: '10px', padding: '10px', backgroundColor: '#f0f0f0' }}>
            <Text>状态: {roomResource.status}</Text>
            <Text> 玩家: {roomResource.playerIps.length}</Text>
            <Text> 回合: {roomResource.round}</Text>
          </View>
        )}
      </View>

      <View style={{ marginBottom: '20px' }}>
        <Input
          placeholder='指令'
          value={command}
          onInput={(e) => setCommand(e.detail.value)}
          style={{ border: '1px solid #ccc', padding: '8px', marginBottom: '8px' }}
        />
        <Input
          placeholder='参数 (JSON)'
          value={commandPayload}
          onInput={(e) => setCommandPayload(e.detail.value)}
          style={{ border: '1px solid #ccc', padding: '8px', marginBottom: '8px' }}
        />
        <Button onClick={handleSendGameCommand} type='primary' disabled={!isConnected}>
          发送指令
        </Button>
      </View>
    </View>
  )
}